package cn.moziware.developdemo.activity;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

import androidx.core.content.FileProvider;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

import cn.moziware.developdemo.R;
import cn.moziware.developdemo.helper.Utils;

/**
 * Activity that shows how open a document on moziware device.
 */
public class UseSystemDocumentViewActivity extends Activity {

    private final String mSampleFileName = "Moziware应用开发指南.pdf";
    private final String mSampleFolderName = "Documents";
    private final String mSampleMimeType = "application/pdf";

    private File mSampleFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.use_system_document_view);

        try {
            mSampleFile = Utils.copyFromAssetsToExternal(this, mSampleFileName, mSampleFolderName);
        } catch (IOException ex) {
            Toast.makeText(this, "Failed to copy pdf file", Toast.LENGTH_LONG).show();
        }
    }

    public void onLaunchDocument(View view) {
        final Uri contentUri = FileProvider.getUriForFile(
                getApplicationContext(),
                getApplicationContext().getPackageName() + ".fileprovider",
                mSampleFile);

        if (mSampleFile == null) {
            Toast.makeText(getApplicationContext(),"Failed to find pdf file",Toast.LENGTH_LONG).show();
            return;
        }

        final Intent viewIntent = new Intent(Intent.ACTION_VIEW);
        viewIntent.addCategory(Intent.CATEGORY_DEFAULT);
        viewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        viewIntent.setDataAndType(contentUri, mSampleMimeType);
        viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        startActivity(viewIntent);
    }
}